<template>
  <div class="app-container">
    <searchForm :formOptions="formOptions" @onSearch="onSearch" @onReset="onReset" :formLabelWidth="formLabelWidth"
      v-show="showSearch" />
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['clr:examineField:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['clr:examineField:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['clr:examineField:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="upload.open = true"
          v-hasPermi="['clr:examineField:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['clr:examineField:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <tableList @handleUpdate="handleUpdate" @handleDelete="handleDelete" @handleSelectionChange="handleSelectionChange"
      :examineFieldList="examineFieldList"></tableList>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 用户导入对话框 -->
    <el-dialog title="excel导入" :visible.sync="upload.open" width="400px" append-to-body>
      <!-- 年级批次:
      <el-select v-model="excelGradeField" placeholder="请选择年级批次" style="width:84%">
        <el-option v-for="dict in dict.type.clr_grade_type" :key="dict.value" :label="dict.label"
          :value="dict.value"></el-option>
      </el-select> -->
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls"
        :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="onSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="templateDownload">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改辅导员考核指标对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="一级指标" prop="cecId">
              <el-select v-model="form.cecId" placeholder="请选择一级指标" @change="handleclassifySelectionChange" clearable
                style="width: 100%;">
                <el-option v-for="item in classifyList" :key="item.CECID" :label="item.CECNAME" :value="item.CECID" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指标名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请输入指标名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高分" prop="score">
              <template>
                <el-input-number v-model.trim="form.score" :min="1" :max="maxScore" label="请输入最高分" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态0:正常1:停用" style="width: 100%;">
                <el-option v-for="dict in dict.type.common_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="考核要点" prop="econtent">
              <editor v-model.trim="form.econtent" :min-height="192" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="赋分办法" prop="scoringWay">
              <editor v-model.trim="form.scoringWay" :min-height="192" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="form.remark" placeholder="请输入备注" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导入成功或失败提示信息" :visible.sync="uploadData" width="500px" append-to-body>
      <el-descriptions :column="1">
        <el-descriptions-item label="上传总数据">{{ studenData.totalSize }}条</el-descriptions-item>
        <el-descriptions-item label="成功数据">{{ studenData.successSize }}条</el-descriptions-item>
        <el-descriptions-item label="失败数据">{{ studenData.errorSize }}条</el-descriptions-item>
        <el-descriptions-item label="失败原因">
          <!-- <span v-html="studenData.failureMsg"></span> -->
          {{ studenData.errorMsg }}
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadData = false">取 消</el-button>
        <el-button type="primary" @click="uploadData = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listExamineField,
  getExamineField,
  delExamineField,
  addExamineField,
  updateExamineField,
  importTemplate
} from "@/api/clr/examineField";
import { getClassifySelector } from "@/api/clr/classify";
import searchForm from "@/components/Search/searchForm.vue";
import tableList from "./componets/tableList.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "ExamineField",
  dicts: ["common_status", "clr_grade_type"],
  components: {
    tableList,
    searchForm
  },
  data() {
    return {
      formLabelWidth: "75px",
      formOptions: [
        {
          label: "一级指标",
          prop: "cecId",
          element: "el-select",
          options: [],
          placeholder: "请选择指标分类"
        },
        {
          label: "指标名称",
          prop: "name",
          element: "el-input",
          placeholder: "请输入指标名称"
        }
      ],
      uploadData: false, // 提示信息弹框
      studenData: {}, //提示返回值
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API + "/clr/examineField/importExamineField"
      },
      // 记录分数最大值
      maxScore: null,
      excelGradeField: '', // 导出传递年级批次
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 辅导员考核指标表格数据
      examineFieldList: [],
      // 指标分类数据
      classifyList: [],
      // 弹出层标题
      title: "",
      activeName: "second",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cecId: null,
        name: null,
        status: null
      },
      names: '',
      examineName: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cecId: [
          { required: true, message: "请选择指标分类", trigger: "change" }
        ],
        name: [{ required: true, message: "请输入指标名称", trigger: "bulr" }],
        score: [{ required: true, message: "请输入内容", trigger: "bulr" }],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        econtent: [{ required: true, message: "请输入内容" }],
        scoringWay: [{ required: true, message: "请输入内容" }]
      }
    };
  },
  created() {
    this.getList();
    this.getClassifySelect();
  },
  methods: {
    // 获取搜索表单提交的数据
    onSearch(val) {
      // 查询条件和分页数据合并
      this.queryParams = Object.assign(this.queryParams, val);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    onReset(data) {
      this.queryParams.pageNum = 1;
      this.queryParams = Object.assign(this.queryParams, data);
      this.getList();
    },
    /** 查询辅导员考核指标列表 */
    getList() {
      this.loading = true;
      listExamineField(this.queryParams).then(response => {
        this.examineFieldList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getClassifySelect() {
      getClassifySelector().then(res => {
        this.classifyList = res.data;
        this.formOptions[0].options = res.data.map(item => {
          return {
            value: item["CECID"],
            label: item["CECNAME"]
          };
        });
      });
    },
    handleClick(tab, event) {
      this.examineFieldList = [];
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cefId);
      this.examineName = selection.map(item => item.classifyName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {};
      this.open = true;
      this.title = "添加辅导员考核指标";
      this.getClassifySelect();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const cefId = row.cefId || this.ids;
      getExamineField(cefId).then(response => {
        this.form = response.data;
        console.log(this.form.score, this.form, "score");
        this.open = true;
        this.title = "修改辅导员考核指标";
        this.handleclassifySelectionChange(response.data.cecId);
        this.getClassifySelect();
      });
    },
    setText(html) {
      return html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
        .replace(/<br\/?>/gi, '\n')
        .replace(/<[^>/]+>/g, '')
        .replace(/(\n)?<\/([^>]+)>/g, '')
        .replace(/\u00a0/g, ' ')
        .replace(/&nbsp;/g, ' ')
        .replace(/<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>/g, '')
        .replace(/<\/?(img|table)[^>]*>/g, "")   // 去除图片和表格
        .replace(/<\/?(a)[^>]*>/g, "")			//  去除a标签
    },
    /** 提交按钮 */
    submitForm() {
      // let data = this.form.scoringWay.replace(/<[^<>]+>/g, "").replace(
      //   /&nbsp;/gi,
      //   ""
      // );
      this.form.econtent = this.setText(this.form.econtent)
      this.form.scoringWay  = this.setText(this.form.scoringWay)
      console.log(this.form,this.form.scoringWay, '富文本')
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cefId != null) {
            updateExamineField(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExamineField(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleclassifySelectionChange(CECID) {
      this.maxScore = null;
      let classify = this.classifyList.filter(data => {
        return data.CECID === CECID;
      });
      this.maxScore = classify[0].SCORE;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cefIds = row.cefId || this.ids;
      this.examineName = row.classifyName || this.examineName;
      this.$modal
        .confirm(
          '是否确认删除考核指标名称为"' + this.examineName + '"的数据项？'
        )
        .then(function () {
          return delExamineField(cefIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 点击确定上传文件按钮
    submitUpload() {
      this.$refs.upload.submit();
    },
    saveAs(obj, fileName) {
      let ele = document.createElement("a");
      ele.download = fileName || "下载"; //下载文件名
      ele.href = URL.createObjectURL(obj); // 绑定a标签
      ele.style.display = "none";
      document.body.appendChild(ele); // 兼容火狐浏览器
      ele.click();
      setTimeout(function () {
        // 延时释放
        URL.revokeObjectURL(obj); // 用 URL.revokeObjectURL() 来释放这个object URL
        document.body.removeChild(ele); // 兼容火狐浏览器
      }, 100);
    },
    //文件上传成功
    onSuccess(response) {
      if (response.code == 200) {
        this.$message.success("文件上传成功");
        this.$refs.upload.clearFiles();
        this.upload.open = false;
        this.uploadData = true;
        this.getList();
      } else {
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.upload.open = false;
        this.uploadData = true;
        this.$message.error("文件上传失败");
        // this.getList();
      }
    },
    // 模板下载
    templateDownload() {
      if (this.excelGradeField) {
        importTemplate({ gradeField: this.excelGradeField }).then(response => {
          // console.log(response, "模板下载");
          this.saveAs(
            new Blob([response], {
              type: "application/vnd.ms-excel;charset=utf-8"
            }),
            `考核指标模板_${new Date().getFullYear()}-${new Date().getMonth() +
            1}-${new Date().getDate()}`
          );
        });
      } else {
        this.$modal.msgWarning('请选择年级批次')
      }

    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "clr/examineField/export",
        {
          ...this.queryParams
        },
        '辅导员考核指标' + `_${new Date().getFullYear()}-${new Date().getMonth() +
        1}-${new Date().getDate()}.xlsx`
      );
    }
  }
};
</script>
